import {
  Modal,
  message
} from 'antd';
import {
  WeaLocaleProvider,
  WeaTools
} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
const confirm = Modal.confirm;
const {
  sendMsg
} = WeaTools;
//发消息、发起群聊
function sendEmessage(emessageId) {
  var isGroup = false;
  if (!!emessageId) {
    if (emessageId.indexOf(",") > -1) {
      isGroup = true;
    }
  }
  if (!emessageId) {
    message.warning(SystemEnv.getHtmlNoteName(4780, readCookie("languageidweaver")));
    return;
  }
  if (emessageId.match(/,$/)) {
    emessageId = emessageId.substring(0, emessageId.length - 1);
  }
  var openType = isGroup ? "2" : "0";
  if (isGroup) {
    confirm({
      content: SystemEnv.getHtmlNoteName(4781, readCookie("languageidweaver")),
      onOk() {
        sendMsgToPC(emessageId, openType, '', '');
      },
      onCancel() {},
    });
  } else {
    sendMsgToPC(emessageId, openType, '', '');
  }
}

/**
 * 调用e-message发起会话
 * @param conventioners
 * @param openType
 * @param groupName
 * @param extra
 */
export function sendMsgToPC(conventioners, openType, groupName, extra, successCallBack, errorCallBack) {
  sendMsg(conventioners, openType, '', '');
  // $.ajax({
  //   url: '/social/im/SocialIMOperation.jsp?operation=openPCconversation',
  //   data: {
  //     conventioners,
  //     openType,
  //     groupName,
  //     extra,
  //   },
  //   type: 'post',
  //   dataType: 'json',
  //   contentType: 'application/x-www-form-urlencoded; charset=utf-8',
  //   success(data) {
  //     if (data != null) {
  //       if (data.pcStatus == 0 && data.webStatus == 0) {
  //         // pc和web都不在
  //         Modal.warning({
  //           title: i18n.confirm.systemhints(),
  //           content: getLabel('386482',"检查到您的web端和客户端的e-message不在线，请打开任意一端进行会话！"),
  //         });
  //       } else if (data.webStatus == 1) {
  //         // web在线
  //         if (window.top.$('#socialIMFrm').length > 0) {

  //         } else {
  //           if (!!window.ActiveXObject || 'ActiveXObject' in window) {
  //             Modal.warning({
  //               title: i18n.confirm.systemhints(),
  //               content: getLabel('386483',"您发起的e-message聊天已经建立，<br>  请到主页进行消息发送！"),
  //             });
  //           }
  //         }
  //       } else {
  //         // pc在线不作判断
  //       }
  //       typeof successCallBack === 'function' && successCallBack(data);
  //     } else {
  //       Modal.warning({
  //         title: i18n.confirm.systemhints(),
  //         content: getLabel('386484',"对话创建失败！"),
  //       });
  //       typeof errorCallBack === 'function' && errorCallBack();
  //     }
  //   },
  //   error(XMLHttpRequest, textStatus, errorThrown) {
  //     Modal.warning({
  //       title: i18n.confirm.systemhints(),
  //       content: getLabel('386485',"请求发送失败，请您检查当前网络！"),
  //     });
  //     typeof errorCallBack === 'function' && errorCallBack();
  //   },
  // });
}

//发送邮件
function sendMail(id) {
  //openFullWindowForXtable("/email/new/MailInBox.jsp?opNewEmail=1&amp;isInternal=1&amp;internalto&id="+id);
  window.open(`/spa/email/static/index.html#/main/email/new?fromPage=hrmCard&internaltonew=[{"id":${id},"type":"resource"}]`);
}

//发送短信
function sendSmsMessage(id) {
  //openFullWindowForXtable("/sms/SmsMessageEdit.jsp?hrmid="+id);
  window.open(`/spa/smallApp/static/index.html#/main/sms/SendSms?hrmid=${id}`);
}

//新建协作
function addCoWork(id) {
  //openFullWindowForXtable("/cowork/AddCoWork.jsp?hrmid=" + id);
  window.open(`/spa/cowork/static/index.html#/main/cowork/main?hrmid=${id}`);

}

//新建日程
function doAddWorkPlanByHrm(id) {
  //openFullWindowForXtable("/workplan/data/WorkPlan.jsp?resourceid="+id+"&add=1")
  window.open(`/spa/workplan/static/index.html#/main/wp/workPlanCreateSingle?type=create&selectedUser=${id}`);
}

//系统信息
function jsHrmResourceSystemView(id) {
  //window.open(`/spa/hrm/index.html#/main/hrm/systeminfo${window.WeaHrm4Formal?'4Formal':''}/${id}`);
  window.open(`/spa/hrm/index_mobx.html#/main/hrm/systeminfo/${id}`);
}

//我的下属--流程
function jsRequestView(id) {
  // openFullWindowForXtable("/workflow/request/RequestView.jsp?resourceid=" + id);
  window.open(`/spa/workflow/index_mobx.jsp#/main/workflow/listDoing?resourceid=${id}`);
}

//我的下属--文档
function docSearch(id) {
  // openFullWindowForXtable('/docs/search/DocSearchTemp.jsp?docstatus=6&hrmresid=' + id);
  window.open(`/spa/document/static/index.html#/main/document/search?doccreaterid=${id}&viewcondition=2`)
}

//我的下属--项目
function doProjcSearch(id) {
  // openFullWindowForXtable("/proj/search/SearchOperation.jsp?member=" + id);
  window.open(`/spa/prj/index.html#/main/prj/mineProject?search_resourceid=${id}`);
}

//我的下属--客户
function openCRM(id) {
  // openFullWindowForXtable('/CRM/search/SearchOperation.jsp?destination=myAccount&resourceid=' + id);
  window.open(`/spa/crm/mobx/index.html#/main/crm/customer/hrmView?searchHrmId=${id}`);
}

//我的下属--资产
function cptSearch(id) {
  // openFullWindowForXtable('/cpt/search/SearchOperation.jsp?resourceid=' + id + '&isdata=2');
  window.open(`/spa/cpt/index.html#/main/cpt/mycapital?hrmid=${id}`);
}

//我的下属--下属
function openHrmResourceView(id) {
  //openFullWindowForXtable("/hrm/HrmTab.jsp?_fromURL=HrmResourceView&id="+id+"&srcid="+id);
  window.open(`/spa/hrm/index_mobx.html#/main/hrm/underling/${id}`);
}

//我的下属--预算
function openFnaBudgetResourceDetail(id) {
  openFullWindowForXtable("/fna/report/budget/FnaBudgetResourceDetail.jsp?resourceid=" + id);
}

//我的下属--收支
function openFnaExpenseResourceDetail(id) {
  // openFullWindowForXtable("/fna/report/expense/FnaExpenseResourceDetail.jsp?resourceid=" + id);
  window.open(`/fna/cm/rpt/PersonalPayments.jsp?hrmResourceID=${id}`)
}


//我的下属--工作报告
function openWorkReport(id) {
  openFullWindowForXtable("/spa/develop/index_mobx.html?#/main/develop/growuplist?userid=" + id);
}

//培训记录--详细信息
function jsTrainRecordShowDetail(id) {
  let dialog = new window.top.Dialog();
  dialog.currentWindow = window;
  const url = "/hrm/HrmDialogTab.jsp?_fromURL=HrmResourceTrainRecordBasic&isdialog=1&id=" + id;
  dialog.Title = getLabel('386486', "培训记录详细信息");
  dialog.Width = 800;
  dialog.Height = 503;
  dialog.Drag = true;
  dialog.URL = url;
  dialog.show();
}

//培训记录--培训安排--申请
function jsHrmTrainApply(trainplanid, applyworkflowid) {
  openFullWindowForXtable("/workflow/request/AddRequest.jsp?workflowid=" + applyworkflowid + "&TrainPlanId=" + trainplanid);
}

//考核奖惩--奖惩情况--详细信息
function jsRewardsRecord2Detial(id) {
  //openFullWindowForXtable("/hrm/HrmDialogTab.jsp?_fromURL=HrmAwardEdit&id="+id+"&cmd=showdetail");
  let dialog = new window.top.Dialog();
  dialog.currentWindow = window;
  dialog.Title = getLabel('386487', "奖惩信息");
  const url = "/hrm/HrmDialogTab.jsp?_fromURL=HrmAwardEdit&id=" + id + "&cmd=showdetail";
  dialog.Width = 800;
  dialog.Height = 500;
  dialog.Drag = true;
  dialog.URL = url;
  dialog.show();
}

function openFullWindowForXtable(url) {
  var redirectUrl = url;
  var width = screen.availWidth - 10;
  var height = screen.availHeight - 60;
  //if (height == 768 ) height -= 75 ;
  //if (height == 600 ) height -= 60 ;
  var szFeatures = "top=0,";
  szFeatures += "left=0,";
  szFeatures += "width=" + width + ",";
  szFeatures += "height=" + height + ",";
  szFeatures += "directories=no,";
  szFeatures += "status=yes,";
  szFeatures += "menubar=no,";
  szFeatures += "scrollbars=yes,";
  szFeatures += "resizable=yes"; //channelmode
  window.open(redirectUrl, "", szFeatures);
}

const openFullWindowHaveBar = (url) => {
  var redirectUrl = url;
  var width = screen.availWidth - 10;
  var height = screen.availHeight - 50;
  var szFeatures = "top=0,";
  szFeatures += "left=0,";
  szFeatures += "width=" + width + ",";
  szFeatures += "height=" + height + ",";
  szFeatures += "directories=no,";
  szFeatures += "status=yes,toolbar=no,location=no,";
  szFeatures += "menubar=no,";
  szFeatures += "scrollbars=yes,";
  szFeatures += "resizable=yes"; //channelmode
  window.open(redirectUrl, "", szFeatures);
}

function getUserName() {
  try {
    let vbsserial = "";
    let hCard = htactx.OpenDevice(1); //打开设备
    if (hCard == 0) {
      message.warning(getLabel('21607', "请确认您已经正确地安装了驱动程序并插入了usb令牌"));
      return vbsserial;
    }

    try {
      vbsserial = htactx.GetUserName(hCard); //获取用户名
      htactx.CloseDevice(hCard)
      return vbsserial;
    } catch (e) {
      message.warning(`${getLabel('21607',"请确认您已经正确地安装了驱动程序并插入了usb令牌")}2`);
      htactx.CloseDevice(hCard);
      return vbsserial;
    }
  } catch (e) {
    message.warning(getLabel('21607', "请确认您已经正确地安装了驱动程序并插入了usb令牌"));
    htactx.CloseDevice(hCard);
    return vbsserial;
  }
}

function chkMail(email) {
  if (email == '') {
    return true;
  }

  let pattern = /^(?:[a-z\d]+[_\-\+\.]?)*[a-z\d]+@(?:([a-z\d]+\-?)*[a-z\d]+\.)+([a-z]{2,})+$/i;
  let chkFlag = pattern.test(email);
  if (chkFlag) {
    return true;
  } else {
    message.warning(getLabel('24570', "邮箱地址的格式不正确"));
    return false;
  }
}

function jumpToHrmCard(id) {
  //window.open(`/spa/hrm/index.html#/main/hrm/resource${window.WeaHrm4Formal?'4Formal':''}/HrmResourceBase${window.WeaHrm4Formal?'4Formal':''}/${id}`);
  window.open(`/spa/hrm/index_mobx.html#/main/hrm/card/cardInfo/${id}`);
}

function jumpToHrmDept(id) {
  //window.open('/hrm/HrmTab.jsp?_fromURL=HrmDepartmentDsp&id=' + id);
  window.open(`/spa/hrm/engine.html#/hrmengine/organization?showTree=false&isView=1&type=department&id=${id}`);
}

function jumpToHrmSubCompany(id) {
  //window.open('/hrm/HrmTab.jsp?_fromURL=HrmSubCompanyDsp&id=' + id);
  window.open(`/spa/hrm/engine.html#/hrmengine/organization?showTree=false&isView=1&type=subcompany&id=${id}`);
}

function jumpToHrmPost(id) {
  // window.open('/hrm/HrmDialogTab.jsp?_fromURL=HrmJobTitlesEdit&id=' + id);
  window.open(`/spa/hrm/engine.html#/hrmengine/posts?id=${id}`);
}

function jumpToHrmJob(id) {
  window.open(`/spa/hrm/engine.html#/hrmengine/singleJob?id=${id}`);
}

function jumpToHrmContract(id) {
  window.open('/hrm/contract/contract/HrmContractView.jsp?id=' + id);
}

//新建流程
function onNewRequest(params) {
  const wfid = params.wfid || '';
  const f_weaver_belongto_userid = params.f_weaver_belongto_userid || '';
  const beagenter = params.beagenter || '';
  const isagent = params.isagent || '';
  //计数
  jQuery.post('/workflow/request/AddWorkflowUseCount.jsp', {
    wfid: wfid
  });
  let paramstr = `workflowid=${wfid}&isagent=${isagent}&beagenter=${beagenter}&f_weaver_belongto_userid=${f_weaver_belongto_userid}&f_weaver_belongto_usertype=0`;
  openFullWindowHaveBar('/workflow/request/CreateRequestForward.jsp?' + paramstr);
}

const openFullWindowHaveBarForWFList = (url, requestid) => {
  try {
    document.getElementById("wflist_" + requestid + "span").innerHTML = "";
  } catch (e) {}
  const redirectUrl = url;
  const width = screen.availWidth - 10;
  const height = screen.availHeight - 50;
  let szFeatures = "top=0,left=0,";
  szFeatures += "width=" + width + ",";
  szFeatures += "height=" + height + ",";
  szFeatures += "directories=no,status=yes,toolbar=no,location=no,";
  szFeatures += "menubar=no,scrollbars=yes,resizable=yes";
  window.open(redirectUrl, "", szFeatures);
}

const viewDepartment = (departmentid) => {
  jumpToHrmDept(departmentid);
}

const viewSubCompany = (subcompanyid) => {
  jumpToHrmSubCompany(subcompanyid);
}

window.viewDepartment = viewDepartment;
window.viewSubCompany = viewSubCompany;
window.openFullWindowHaveBarForWFList = openFullWindowHaveBarForWFList;

export {
  sendEmessage,
  sendMail,
  sendSmsMessage,
  addCoWork,
  doAddWorkPlanByHrm,
  jsHrmResourceSystemView,
  openFullWindowForXtable,
  jsRequestView,
  docSearch,
  doProjcSearch,
  openCRM,
  cptSearch,
  openHrmResourceView,
  openFnaBudgetResourceDetail,
  openFnaExpenseResourceDetail,
  openWorkReport,
  jsTrainRecordShowDetail,
  jsHrmTrainApply,
  jsRewardsRecord2Detial,
  getUserName,
  chkMail,
  jumpToHrmCard,
  jumpToHrmDept,
  jumpToHrmSubCompany,
  jumpToHrmPost,
  jumpToHrmContract,
  onNewRequest,
}